package sino.flux.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/test")
public class TestController {
	private static final Logger log = LogManager.getLogger();
	
	// 普通的SpringMVC方法
	@GetMapping("/1")
	private String get1() {
	    log.info("get1 start");
	    String result = createStr();
	    log.info("get1 end.");
	    return result;
	}
	
	
	// WebFlux(返回的是Mono)
	@GetMapping("/2")
	private Mono<String> get2() {
		
		
	    log.info("get2 start");
	    Mono<String> result = Mono.fromSupplier(() -> createStr());
	    log.info("get2 end.");
	    
	    return result;
	}
	
	
	// 阻塞5秒钟
	private String createStr() {
	    try {
	        TimeUnit.SECONDS.sleep(5);
	    } catch (InterruptedException e) {
	    }
	    return "some string";
	}
	
	
	/**
	 * 页面响应式输出
	 * 
	 * html页面可使用如下脚本
	 * 
	 * var es = new EventSource("http://localhost:8111/test/3")
	 * es.addEventListener("open",function(){console.info("连接成功")},false)
	 * es.addEventListener("message",function(e){console.info(e.data)},false)
	 * es.addEventListener("error",function(e){console.info(e)},false)
	 * 
	 * @return
	 */
	@GetMapping(value = "/3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	private Flux<String> flux() {
	    Flux<String> result = Flux
	        .fromStream(IntStream.range(1, 200).mapToObj(i -> {
	            try {
	                TimeUnit.SECONDS.sleep(1);
	            } catch (InterruptedException e) {
	            }
	            return "推送数据-->" + i;
	        }));
	    return result;
	}
}
